import pandas as pd
import numpy as np
from pyecharts import options as opts
from pyecharts.charts import Bar
from pyecharts.faker import Faker
# from pyecharts.globals import ThemeType

class BarChart_flow_month_1year():
    
    def __init__(self, dataset, place=1, year='2017'):
        self.paint_data=dataset
        self.place=place #九寨沟——0；四姑娘山——1
        self.year=year
        
        #主程序入口
        self.main()
    
    #主程序入口函数实现
    def main(self):
        
        # 调用获取数据函数
        self.getData()
        # 调用绘制条形图函数
        self.paintBarChart()
        
    
    #获取数据
    def getData(self):
            
        df=self.paint_data.loc[:,['date','flow']] #取出数据集中的日期和客流数据
        
        df.columns = ['date','flow'] #表头名称

        df['date'] = pd.to_datetime(df['date']) #将数据类型转换为日期类型
        df = df.set_index('date') # 将date设置为index      
        self.paint_data=df
        
    
    def paintBarChart(self):
        
        #设置横纵坐标
        months = ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月']
        
        if self.place==0:
            title="九寨沟"+self.year+"年月平均客流"
        else:
            title="四姑娘山"+self.year+"年月平均客流"
        
        fileName='1.5 '+title+"条形图.html"
        
        weather=self.paint_data[self.year] #筛选某一年的天气数据
       
        flow_month_nums=[0,0,0,0,0,0,0,0,0,0,0,0,0]
        flow_month_avgs=[0,0,0,0,0,0,0,0,0,0,0,0,0]
        month_daynums = [0,0,0,0,0,0,0,0,0,0,0,0,0]
            
        for j in range(1,13):
            for flowday in weather[self.year+'-{}'.format(j)].values:
                flow_month_nums[j]+=flowday
                month_daynums[j]+=1
            flow_month_nums[j]=int(flow_month_nums[j])
            flow_month_avgs[j]=flow_month_nums[j]/month_daynums[j]

        value=flow_month_avgs[1:13]
        value=np.array(value)
        value=np.round(value,2).tolist()
        
        c = (
            # Bar(init_opts=opts.InitOpts(theme=ThemeType.DARK, width="900px", height="600px"))
            Bar(init_opts=opts.InitOpts(width="900px", height="600px"))
            .add_xaxis(months)
            .add_yaxis("客流", value, color=Faker.rand_color())
            .set_global_opts(
                title_opts=opts.TitleOpts(title=title),
                datazoom_opts=opts.DataZoomOpts(type_="inside"),
            )
            .render('resultFile/'+fileName)
        )
        
        print(fileName+"已生成！")

